package com.snail.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.common.core.constant.CommonConstants;
import com.snail.common.core.constant.UserConstants;
import com.snail.common.core.exception.ServiceException;
import com.snail.common.core.utils.PageUtils;
import com.snail.common.core.utils.SpringUtils;
import com.snail.common.core.utils.StringUtils;
import com.snail.common.core.utils.ValidationUtils;
import com.snail.common.core.utils.bean.BeanUtils;
import com.snail.common.core.utils.bean.BeanValidators;
import com.snail.common.core.utils.sql.SqlUtil;
import com.snail.common.core.web.page.PageResult;
import com.snail.common.security.utils.SecurityUtils;
import com.snail.system.api.domain.*;
import com.snail.system.api.dto.SysUserDto;
import com.snail.system.api.query.SysUserQuery;
import com.snail.system.mapper.*;
import com.snail.system.service.ISysConfigService;
import com.snail.system.service.ISysDeptService;
import com.snail.system.service.ISysUserService;
import com.snail.workflow.api.constant.WorkflowConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author snail
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);


    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysDeptService sysDeptService;

    @Override
    public PageResult<SysUserDto> selectUserPage(SysUserQuery query) {
        Page<SysUserDto> page = PageUtils.buildPage(query);
        if (StringUtils.isNotEmpty(query.getDeptId())) {
            query.setDeptId(SqlUtil.parseLike(query.getDeptId()));
        }
        page = baseMapper.selectUserPage(page, query);
        return PageUtils.pageResult(page);
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUserDto> selectUserList(SysUserQuery user) {
        SysDept sysDept = SecurityUtils.getSysDept();
        if (StringUtils.isNotEmpty(user.getOrgFilterType())) {
            switch (user.getOrgFilterType()) {
                // 当前组织
                case WorkflowConstants.FILTER_ORG_TYPE_1:
                    user.setDeptId(sysDept.getDeptId());
                    break;
                //当前组织及下属组织
                case WorkflowConstants.FILTER_ORG_TYPE_2:
                    user.setDeptId(SqlUtil.parseLike(sysDept.getDeptId()));
                    break;
                //上级组织
                case WorkflowConstants.FILTER_ORG_TYPE_3:
                    user.setDeptId(sysDept.getParentId());
                    break;
                //上级组织及下属组织
                case WorkflowConstants.FILTER_ORG_TYPE_4:
                    user.setDeptId(SqlUtil.parseLike(sysDept.getParentId()));
                    break;
                //指定组织
                case WorkflowConstants.FILTER_ORG_TYPE_5:
                    //由前端传指定的组织数据
                    break;
                default:
                    break;
            }
        }
        return baseMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUserDto> selectAllocatedList(SysUserQuery user) {
        return baseMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUnallocatedList(SysUserQuery user) {
        return baseMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUserDto selectUserInfoByUserName(String userName) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName, userName);
        List<SysUser> userList = baseMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(userList)) {
            return null;
        }
        SysUser sysUser = userList.get(0);

        SysUserDto userDto = new SysUserDto();
        BeanUtils.copyProperties(sysUser, userDto);
        //角色
        List<SysRole> roleList = userRoleMapper.getRoleByUserId(sysUser.getUserId());
        userDto.setRoles(roleList);
        //部门信息
        SysDept sysDept = sysDeptService.getById(sysUser.getDeptId());
        userDto.setDept(sysDept);
        return userDto;
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUserDto selectUserByUserName(String userName) {
        return selectUserInfoByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(String userId) {
        return baseMapper.selectById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        SysUser info = baseMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && !info.getUserId().equals(user.getUserId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        SysUser info = baseMapper.checkPhoneUnique(user.getPhoneNumber());
        if (StringUtils.isNotNull(info) && !info.getUserId().equals(user.getUserId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        SysUser info = baseMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && !info.getUserId().equals(user.getUserId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && SecurityUtils.isAdminUser(user.getUserId())) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(String userId) {
        if (!SecurityUtils.isAdminUser()) {
            SysUserQuery user = new SysUserQuery();
            user.setUserId(userId);
            SysUser sysUser = SpringUtils.getAopProxy(this).selectUserById(userId);
            if (sysUser == null) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param userDto 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUserDto userDto) {
        if (!this.checkUserNameUnique(userDto)) {
            throw new ServiceException("新增用户'" + userDto.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(userDto.getPhoneNumber()) && !this.checkPhoneUnique(userDto)) {
            throw new ServiceException("新增用户'" + userDto.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(userDto.getEmail()) && !this.checkEmailUnique(userDto)) {
            throw new ServiceException("新增用户'" + userDto.getUserName() + "'失败，邮箱账号已存在");
        }
        SysDept sysDept = sysDeptService.getById(userDto.getDeptId());
        if (sysDept != null) {
            userDto.setTenantId(sysDept.getTenantId());
        }
        userDto.setPassword(SecurityUtils.encryptPassword(userDto.getPassword()));
        // 新增用户信息
        int rows = baseMapper.insert(userDto);
        // 新增用户岗位关联
        insertUserPost(userDto);
        // 新增用户与角色管理
        insertUserRole(userDto);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return baseMapper.insert(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param userDto 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUserDto userDto) {
        this.checkUserAllowed(userDto);
        this.checkUserDataScope(userDto.getUserId());
        if (!this.checkUserNameUnique(userDto)) {
            throw new ServiceException("修改用户'" + userDto.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(userDto.getPhoneNumber()) && !this.checkPhoneUnique(userDto)) {
            throw new ServiceException("修改用户'" + userDto.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(userDto.getEmail()) && !this.checkEmailUnique(userDto)) {
            throw new ServiceException("修改用户'" + userDto.getUserName() + "'失败，邮箱账号已存在");
        }
        String userId = userDto.getUserId();
        SysDept sysDept = sysDeptService.getById(userDto.getDeptId());
        if (sysDept != null) {
            userDto.setTenantId(sysDept.getTenantId());
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(userDto);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(userDto);
        return baseMapper.updateById(userDto);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(String userId, String[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return baseMapper.updateById(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return baseMapper.updateById(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return baseMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setPasswordModifyTime(LocalDateTime.now());
        return baseMapper.updateById(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return baseMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param userDto 用户对象
     */
    public void insertUserRole(SysUserDto userDto) {
        this.insertUserRole(userDto.getUserId(), userDto.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param userDto 用户对象
     */
    public void insertUserPost(SysUserDto userDto) {
        String[] posts = userDto.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (String postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(userDto.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(String userId, String[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (String roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(String userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return baseMapper.deleteById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(String[] userIds) {
        for (String userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return baseMapper.deleteBatchIds(Arrays.asList(userIds));
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = baseMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    baseMapper.insert(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    baseMapper.updateById(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public SysUserDto selectUserInfoById(String userId) {
        SysUser sysUser = getById(userId);
        if (sysUser == null) {
            throw new ServiceException("用户信息不存在!");
        }
        SysUserDto dto = new SysUserDto();
        BeanUtils.copyProperties(sysUser, dto);
        SysDept sysDept = sysDeptService.getById(sysUser.getDeptId());
        dto.setDept(sysDept);
        return dto;
    }

    @Override
    public List<SysUserDto> selectUserInfoByIds(String userIds) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysUser::getUserId, Arrays.asList(userIds.split(CommonConstants.SPLIT_CHAR_1)));
        List<SysUser> userList = baseMapper.selectList(queryWrapper);
        return userList.stream().map(item -> {
            SysUserDto dto = new SysUserDto();
            BeanUtils.copyProperties(item, dto);
            SysDept sysDept = sysDeptService.getById(item.getDeptId());
            dto.setDept(sysDept);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<SysUserDto> selectRoleUserInfo(String roleIds) {
        List<SysUserDto> userList = userRoleMapper.getUserByRoleIds(Arrays.asList(roleIds.split(CommonConstants.SPLIT_CHAR_1)));
        return userList.stream().map(item -> {
            SysUserDto dto = new SysUserDto();
            BeanUtils.copyProperties(item, dto);
            SysDept sysDept = sysDeptService.getById(item.getDeptId());
            dto.setDept(sysDept);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public SysUserDto selectUserInfoByPhone(String phone) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getPhoneNumber, phone);
        List<SysUser> userList = baseMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(userList)) {
            return null;
        }
        SysUser sysUser = userList.get(0);

        SysUserDto userDto = new SysUserDto();
        BeanUtils.copyProperties(sysUser, userDto);
        //角色
        List<SysRole> roleList = userRoleMapper.getRoleByUserId(sysUser.getUserId());
        userDto.setRoles(roleList);
        //部门信息
        SysDept sysDept = sysDeptService.getById(sysUser.getDeptId());
        userDto.setDept(sysDept);
        return userDto;
    }

    @Override
    public String checkExcelData(SysUserDto sysUserDto) {
        StringBuffer error = new StringBuffer();
        ValidationUtils.checkProperty(validator, sysUserDto, Collections.singletonList("deptId"), SysUserDto.class, error);
        if (StringUtils.isNotEmpty(sysUserDto.getUserCode())) {
            ValidationUtils.isTrue(checkUserCodeUnique(sysUserDto), "用户[" + sysUserDto.getNickName() + "]已存在!", error);
        }
        if (StringUtils.isNotEmpty(sysUserDto.getDeptCode())) {
            SysDept sysDept = sysDeptService.selectDeptByCode(sysUserDto.getDeptCode());
            ValidationUtils.isNull(sysDept, "部门[" + sysUserDto.getDeptName() + "]不存在!", error);
            if (sysDept != null) {
                sysUserDto.setDeptId(sysDept.getDeptId());
                sysUserDto.setTenantId(sysDept.getTenantId());
            }
        }
        if (StringUtils.isNotEmpty(sysUserDto.getEmail())) {
            ValidationUtils.isTrue(!checkEmailUnique(sysUserDto), "邮箱[" + sysUserDto.getEmail() + "]已存在!", error);
        }
        if (StringUtils.isNotEmpty(sysUserDto.getPhoneNumber())) {
            ValidationUtils.isTrue(!checkPhoneUnique(sysUserDto), "手机号码[" + sysUserDto.getPhoneNumber() + "]已存在!", error);
        }
        return error.toString();
    }

    /**
     * 校验用户编码是否已存在
     *
     * @param sysUserDto 用户信息
     * @return 结果
     */
    private boolean checkUserCodeUnique(SysUserDto sysUserDto) {
        SysUser sysUser = selectUserByCode(sysUserDto.getUserCode());
        if (sysUser != null && !sysUser.getUserId().equals(sysUserDto.getUserId())) {
            return UserConstants.UNIQUE;
        }
        return UserConstants.NOT_UNIQUE;
    }

    /**
     * 根据用户编码查询用户信息
     *
     * @param userCode 用户编码
     * @return
     */
    private SysUser selectUserByCode(String userCode) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserCode, userCode);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void saveExcelData(List<SysUserDto> dataList) {
        String password = configService.selectConfigByKey("sys.user.initPassword");
        List<SysUser> userList = dataList.stream().map(user -> {
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(user, sysUser);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setStatus(CommonConstants.STATUS_YES);
            return sysUser;
        }).collect(Collectors.toList());
        saveBatch(userList);
    }
}
